package com.example.mumu.passwordbook;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mumu.passwordbook.common.Constants;
import com.example.mumu.passwordbook.common.SwipeMenuAdapter;
import com.example.mumu.passwordbook.dao.AccountDao;
import com.example.mumu.passwordbook.domain.Account;
import com.example.mumu.passwordbook.domain.TypeEnum;
import com.zhouyou.recyclerview.adapter.BaseRecyclerViewAdapter;
import com.zhouyou.recyclerview.divider.HorizontalDividerItemDecoration;
import com.zhouyou.recyclerview.divider.XHorizontalDividerItemDecoration;
import com.zhouyou.recyclerview.swipemenu.SwipeMenuRecyclerView;

import java.util.ArrayList;
import java.util.List;

import static com.example.mumu.passwordbook.common.Constants.Code.REQUEST_ACCOUNT_OPERATE;
import static com.example.mumu.passwordbook.common.Constants.Code.RESPONSE_ACCOUNT_ADD;
import static com.example.mumu.passwordbook.common.Constants.Code.RESPONSE_ACCOUNT_EDIT;
import static com.example.mumu.passwordbook.common.Constants.PreferenceKeys.*;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, SwipeMenuRecyclerView.LoadingListener {

    private SwipeMenuRecyclerView listView;
    private List<Account> accountList;
    private AccountDao accountDao;
    private SwipeMenuAdapter swipeMenuAdapter;
    private ListView lv_search;
    private List<String> l_search;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, AddAccountActivity.class);
                startActivityForResult(intent, 1);
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        //设置首选项,第一次调用时设置默认值
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

        //判断是否需要图案密码
        boolean isPatternLock = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(IS_PATTERN_UNLOCK, true);
        if (isPatternLock) {
            Intent intent = new Intent(this, PatternLockActivity.class);
            startActivity(intent);
        }

        accountDao = new AccountDao(this);

        setupList();


    }


    public void setupSearch(SearchView searchView) {

        searchView.setSubmitButtonEnabled(true);

        lv_search = new ListView(this);
        l_search = new ArrayList<>();
        for (Account account : accountList) {
            l_search.add(account.getName());
        }
        lv_search.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, l_search));
        lv_search.setTextFilterEnabled(true);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                TextView tv_type = findViewById(R.id.tv_type);
                TypeEnum type = (TypeEnum) tv_type.getTag();
                accountList.clear();
                accountList.addAll(accountDao.selectByNameAndType(query, type));
                swipeMenuAdapter.notifyDataSetChanged();
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                if (TextUtils.isEmpty(newText)) {
                    lv_search.clearTextFilter();
                } else {
                    lv_search.setFilterText(newText);
                }
                return true;
            }
        });
    }


    public void setupList() {


        accountList = accountDao.selectByType(null);
        listView = findViewById(R.id.rv_account);

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        listView.setLayoutManager(layoutManager);
        listView.setLoadingListener(this);
        listView.setSwipeDirection(SwipeMenuRecyclerView.DIRECTION_LEFT);//左滑（默认）
        listView.addItemDecoration(new XHorizontalDividerItemDecoration.Builder(this).showLastDivider().margin(dp2px(72), 0).build());

        //添加一个头部view
        View headerView = LayoutInflater.from(this).inflate(R.layout.item_list_account_header, listView, false);
        listView.addHeaderView(headerView);

        swipeMenuAdapter = new SwipeMenuAdapter(this, accountDao);

        swipeMenuAdapter.setOnItemClickListener(new BaseRecyclerViewAdapter.OnItemClickListener<Account>() {
            @Override
            public void onItemClick(View view, Account item, int position) {
                Toast.makeText(MainActivity.this, item.getName(), Toast.LENGTH_SHORT).show();
            }
        });

        listView.setAdapter(swipeMenuAdapter);

        swipeMenuAdapter.setListAll(accountList);


    }


    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchItem.getActionView();
        //初始化搜索功能
        setupSearch(searchView);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_settings) {
//            return true;
//        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        TextView tvType = findViewById(R.id.tv_type);

        if (item.getGroupId() == R.id.group_type) {
            //清空绑定的数据
            if (id == R.id.nav_all) {
                swipeMenuAdapter.replaceAll(accountDao.selectByType(null));
                tvType.setText(R.string.all);
                tvType.setTag(null);
            } else if (id == R.id.nav_social) {
                swipeMenuAdapter.replaceAll(accountDao.selectByType(TypeEnum.social));
                tvType.setText(R.string.social);
                tvType.setTag(TypeEnum.social);
            } else if (id == R.id.nav_financial) {
                swipeMenuAdapter.replaceAll(accountDao.selectByType(TypeEnum.financial));
                tvType.setText(R.string.financial);
                tvType.setTag(TypeEnum.financial);
            } else if (id == R.id.nav_entertainment) {
                swipeMenuAdapter.replaceAll(accountDao.selectByType(TypeEnum.entertainment));
                tvType.setText(R.string.entertainment);
                tvType.setTag(TypeEnum.entertainment);
            } else if (id == R.id.nav_study) {
                swipeMenuAdapter.replaceAll(accountDao.selectByType(TypeEnum.study));
                tvType.setText(R.string.study);
                tvType.setTag(TypeEnum.study);
            } else if (id == R.id.nav_life) {
                swipeMenuAdapter.replaceAll(accountDao.selectByType(TypeEnum.life));
                tvType.setText(R.string.life);
                tvType.setTag(TypeEnum.life);
            } else if (id == R.id.nav_other) {
                swipeMenuAdapter.replaceAll(accountDao.selectByType(TypeEnum.other));
                tvType.setText(R.string.other);
                tvType.setTag(TypeEnum.other);
            }
        }

        if (item.getGroupId() == R.id.group_settings) {
            switch (id) {
                case R.id.nav_settings:
                    Intent intent = new Intent(this, SettingsActivity.class);
                    startActivity(intent);
                    break;
            }
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    /**
     * 响应启动的activity返回的结果
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_ACCOUNT_OPERATE) {

            TextView tv_type = findViewById(R.id.tv_type);
            TypeEnum type = (TypeEnum) tv_type.getTag();

            switch (requestCode) {
                case RESPONSE_ACCOUNT_ADD:
                    swipeMenuAdapter.replaceAll(accountDao.selectByType(type));
                    break;
                case RESPONSE_ACCOUNT_EDIT:
                    swipeMenuAdapter.replaceAll(accountDao.selectByType(type));
                    break;
            }
        }


    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                listView.refreshComplete();
            }
        }, 400);
    }

    @Override
    public void onLoadMore() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                listView.loadMoreComplete();
            }
        }, 400);
    }
}
